package com.baor.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baor.dao.Equipment_abnormalityDao;
import com.baor.domain.Equipment;
import com.baor.domain.UserVO;
import com.baor.domain.Equipment_abnormality;
import com.baor.domain.ExceptionReportVO;
import com.baor.service.ExceptionReportService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//设备异常上报
@Slf4j
@Service
public class ExceptionReportServiceImpl implements ExceptionReportService {
    @Autowired
    private Equipment_abnormalityDao EquipmentReportDao;
    /**
     * 总列表
     *
     * @param params
     * @return
     */
    @Override
    public R getList(Map<String, Object> params) {
        Page page = new Page();
        page.setCurrent((Integer) params.get("pageIndex"));
        page.setSize((Integer) params.get("pageSize"));
        MPJLambdaWrapper<Equipment_abnormality> wrapper = new MPJLambdaWrapper<>(Equipment_abnormality.class)
                .select(Equipment_abnormality::getId,
                        Equipment_abnormality::getAbnormalDescription,
                        Equipment_abnormality::getReportUserId,
                        Equipment_abnormality::getReportTime,
                        Equipment_abnormality::getReviewerUserId,//审核人
                        Equipment_abnormality::getReviewerTime,//审核状态
                        Equipment_abnormality::getReportStatus,//上报状态
                        Equipment_abnormality::getAbnormalType,
                        Equipment_abnormality::getRemarks)
                .select(Equipment::getCode,
                        Equipment::getAddress)
                .selectAs("reviewer.username", ExceptionReportVO::getReviewerUsername)
                .selectAs("reporter.username", ExceptionReportVO::getReportUsername)
                .leftJoin(UserVO.class, "reviewer", UserVO::getId, Equipment_abnormality::getReviewerUserId)
                .leftJoin(UserVO.class, "reporter", UserVO::getId, Equipment_abnormality::getReportUserId)
                .leftJoin(Equipment.class, Equipment::getId, Equipment_abnormality::getEquipmentId)
                .orderByDesc(Equipment_abnormality::getReportTime);
        String code = (String) params.get("code");
        Integer ReportStatus = (Integer) params.get("reportStatus");
        String community = (String) params.get("community");
        // 添加设备编号
        if (StringUtils.hasText(code)) {
            wrapper.like(Equipment::getCode, code);
        }
        if(StringUtils.hasText(community)){
            wrapper.like(Equipment::getCommunity, community);
        }
        // 添加处理状态
        if (ReportStatus != null) {
            wrapper.like(Equipment_abnormality::getReportStatus, ReportStatus);
        }
        Page<ExceptionReportVO> Page = this.EquipmentReportDao.selectJoinPage(page, ExceptionReportVO.class, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("totalSize", Page.getTotal());
        map.put("List", Page.getRecords());
        return R.ok(map);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public R getInfo(Integer id) {
        log.info("查询的数据id：", id);
        MPJLambdaWrapper<Equipment_abnormality> wrapper = new MPJLambdaWrapper<>(Equipment_abnormality.class)
                .select(Equipment_abnormality::getId,
                        Equipment_abnormality::getAbnormalDescription,
                        Equipment_abnormality::getReportUserId,
                        Equipment_abnormality::getReportTime,
                        Equipment_abnormality::getReviewerUserId,
                        Equipment_abnormality::getReviewerTime,
                        Equipment_abnormality::getMaterial,
                        Equipment_abnormality::getResult,
                        Equipment_abnormality::getReportStatus,
                        Equipment_abnormality::getAbnormalType,
                        Equipment_abnormality::getRemarks)
                .select(Equipment::getCode)
                .selectAs("reviewer.username", ExceptionReportVO::getReviewerUsername)
                .selectAs("reporter.username", ExceptionReportVO::getReportUsername)
                .leftJoin(UserVO.class, "reviewer", UserVO::getId, Equipment_abnormality::getReviewerUserId)
                .leftJoin(UserVO.class, "reporter", UserVO::getId, Equipment_abnormality::getReportUserId)
                .leftJoin(Equipment.class, Equipment::getId, Equipment_abnormality::getEquipmentId)
                .eq(Equipment_abnormality::getId, id);
        List<ExceptionReportVO> list = this.EquipmentReportDao.selectJoinList(ExceptionReportVO.class, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("List", list);
        return R.ok(map);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public R del(Integer id) {
        int row = this.EquipmentReportDao.deleteById(id);
        return row > 0 ? R.ok("删除成功") : R.er("删除失败");
    }

    /**
     * 修改
     *
     * @param params
     * @return
     */
    /**
     * 修改设备异常报告 - 使用.set()方式
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R update(Map<String, Object> params) {
        log.info("修改设备异常报告数据：{}", params);
        try {
            // 1. 执行更新操作
            LambdaUpdateWrapper<Equipment_abnormality> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Equipment_abnormality::getId, params.get("id"))
                    .set(Equipment_abnormality::getAbnormalType, params.get("abnormalType"))
                    .set(Equipment_abnormality::getAbnormalDescription, params.get("abnormalDescription"))
                    .set(Equipment_abnormality::getRemarks, params.get("remarks"))
                    .set(Equipment_abnormality::getReviewerUserId, params.get("reviewerUserId"))
                    .set(Equipment_abnormality::getReviewerTime, LocalDateTime.now())
                    .set(Equipment_abnormality::getReportStatus, params.get("reportStatus"));
            int updateCount = this.EquipmentReportDao.update(null, wrapper);

            if (updateCount <= 0) {
                return R.er("更新失败，未找到对应记录");
            }
            MPJLambdaWrapper<Equipment_abnormality> queryWrapper = new MPJLambdaWrapper<>(Equipment_abnormality.class)
                    .select(Equipment_abnormality::getId,
                            Equipment_abnormality::getAbnormalDescription,
                            Equipment_abnormality::getReportUserId,
                            Equipment_abnormality::getReportTime,
                            Equipment_abnormality::getReviewerUserId,
                            Equipment_abnormality::getReviewerTime,
                            Equipment_abnormality::getReportStatus,
                            Equipment_abnormality::getAbnormalType,
                            Equipment_abnormality::getRemarks)
                    .select(Equipment::getCode,
                            Equipment::getCommunity)
                    .selectAs("reviewer.username", ExceptionReportVO::getReviewerUsername)
                    .selectAs("reporter.username", ExceptionReportVO::getReportUsername)
                    .leftJoin(UserVO.class, "reviewer", UserVO::getId, Equipment_abnormality::getReviewerUserId)
                    .leftJoin(UserVO.class, "reporter", UserVO::getId, Equipment_abnormality::getReportUserId)
                    .leftJoin(Equipment.class, Equipment::getId, Equipment_abnormality::getEquipmentId)
                    .eq(Equipment_abnormality::getId, params.get("id"));
            ExceptionReportVO updatedData = this.EquipmentReportDao.selectJoinOne(ExceptionReportVO.class, queryWrapper);
            if (updatedData == null) {
                return R.er("更新成功，但查询更新后数据失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("List", updatedData);
            map.put("message", "修改成功");

            return R.ok(map);
        } catch (Exception e) {
            log.error("修改异常报告失败", e);
            return R.er("修改失败: " + e.getMessage());
        }
    }
}
